/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/read-n-characters-given-read4-ii-call-multiple-times
   @Language: C++
   @Datetime: 20-01-16 14:04
   */

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
	char mBuffer[4]={0,0,0,0};
	int mOffset=0, mSize=0;
public:
	/**
	 * @param buf destination buffer
	 * @param n maximum number of characters to read
	 * @return the number of characters read
	 */
	int read(char *buf, int n) {
		// Write your code here
		int size = 0;
		while(size<n){
			if (mOffset==mSize){
				mOffset=0;
				mSize=read4(mBuffer);
				if (mSize==0) break;
			}
			for(; size<n && mOffset<mSize; buf[size++]=mBuffer[mOffset++]);
		}
		return size;
	}
};
